import Taro, {Component, useCallback, useState} from '@tarojs/taro'
import {Button, Text, View} from '@tarojs/components'

export default class Xhl4 extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isToggleOn1: '我是子元素1',
      isToggleOn2: '我是子元素2'
    }
  }

  config = {
    navigationBarTitleText: '事件处理'
  }

  onClick1 = (e) => {
    //阻止事件冒泡
    e.stopPropagation()
    this.setState({
      isToggleOn1: '我是子元素1，我被点击了'
    })
  }
  onClick2 = () => {
    this.setState({
      isToggleOn2: '我是子元素2，我被点击了'
    })
  }
  onClickParent1 = () => {
    this.setState({
      isToggleOn1: '我是父元素，冒泡了'
    })
  }
  onClickParent2 = () => {
    this.setState({
      isToggleOn2: '我是父元素，冒泡了'
    })
  }

  onActivateLasers (e) {
    console.log(e);
  }

  onThree (p, e) {
    e.stopPropagation()
    console.log(p)
  }

  onFour = (p) => (e) => {
    e.stopPropagation()
    console.log(p);
  }

  render() {
    const [c1, setC1] = useState(0);
    const [c2, setC2] = useState(0);
    const [c3, setC3] = useState(0);

    const increment = c => c + 1

    // 只有 useCallback 对应的 c1 或 c2 的值改变时，才会返回新的函数
    const increment1 = useCallback(() => setC1(increment), [c1]);
    const increment2 = useCallback(() => setC2(increment), [c2]);
    return (
      <View>
        <View>1. 任何组件的事件传递都要以 on 开头</View>
        <Button onClick={this.onActivateLasers}>
          Activate Lasers
        </Button>
        <View>2. 你不能使用 catchEvent 的方式阻止事件冒泡。你必须明确的使用 stopPropagation</View>
        <View onClick={this.onClickParent1}>
          <Button onClick={this.onClick1}>
            {this.state.isToggleOn1}
          </Button>
        </View>
        <View onClick={this.onClickParent2}>
          <Button onClick={this.onClick2}>
            {this.state.isToggleOn2}
          </Button>
        </View>
        <View>3. 向事件处理程序传递参数，事件对象 e 要排在所传递参数的后面</View>
        <Button onClick={this.onThree.bind(this, '参数')}>
          Activate Lasers
        </Button>
        <View>4. 除了 bind 和匿名函数之外，事件参数也可以使用柯里化传参</View>
        <Button onClick={this.onFour('参数')}>
          Activate Lasers
        </Button>
        <View>5. 在函数式组件中，事件传参可以传入事件的引用也可以传入匿名函数</View>
        <View>
          <Text> Counter 1 is {c1} </Text>
          <Text> Counter 2 is {c2} </Text>
          <Text> Counter 3 is {c3} </Text>
        </View>
        <View>
          <Button onClick={increment1}>Increment Counter 1</Button>
          <Button onClick={increment2}>Increment Counter 2</Button>
          <Button onClick={() => setC3(increment)}>Increment Counter 3</Button>
        </View>
      </View>
    )
  }
}
